import Vue from 'vue';
import axios from 'axios';
// import store from '@/store'
import router from '@/router';
import { Modal } from 'ant-design-vue';
import { USERINFO, ACCESS_TOKEN } from '@/store/mutation-types';
import VueAxios from './axios';
import { AESEncrypt } from '@/utils/utils';

// 创建 axios 实例
console.log(process.env.VUE_APP_USE_MOCK);
const service = axios.create({
  baseURL: process.env.VUE_APP_USE_MOCK == true ? '/mock' : process.env.VUE_APP_SERVER_URL, // api base_url
  timeout: 60 * 1000, // 请求超时时间
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
});

const err = (error) => {
  console.log(error.response);
  if (error.response) {
    const { data } = error.response;
    // const token = Vue.ls.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      Modal.error({ title: data.errorMsg });
    }
    if (error.response.status === 401) {
      Vue.ls.clear();
      Vue.ss.clear();
      Modal.destroyAll();
      Modal.error({ title: '没有权限或未登录' });
      router.push('/user/login');
    }
  }

  return Promise.reject(error);
};

// request interceptor
service.interceptors.request.use((Config) => {
  const config = Config;
  const info = Vue.ls.get(USERINFO);
  if (info) {
    config.headers['X-Access-Token'] = AESEncrypt(Vue.ls.get(ACCESS_TOKEN));
    config.headers['X-Access-UserId'] = AESEncrypt(info.uid);
    // config.headers.Authorization = token; // 如果有 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  return config;
}, err);

// response interceptor
service.interceptors.response.use((response) => response, err);

const installer = {
  vm: {},
  // eslint-disable-next-line no-shadow
  install(Vue) {
    Vue.use(VueAxios, service);
  }
};

export {
  installer as VueAxios,
  service as axios
};
